import json

from django.http import JsonResponse
from django.views import View
from app1.models import BookInfo
from django.shortcuts import render


# Create your views here.
def login(request):
    body_json = request.body.decode()
    body_dict = json.loads(body_json)
    name = body_dict.get('name')
    pwd = body_dict.get('pwd')
    print(name)
    print(pwd)
    print(55555)
    if not all([name, pwd]):
        resp = {
            'code': 403,
            'msg': "参数不全"
        }
        return JsonResponse(resp)

    if name == 'zhangsan' and pwd == '1234':
        print(66666)
        resp = {
            'code': 200,
            'msg': "登录成功",
            'data': {
                'id': 1,
                'name': '张三',
                'age': 18
            }
        }
        print(JsonResponse(resp))
        return JsonResponse(resp)


class BooksView(View):
    def get(self, request):
        books = BookInfo.objects.filter(is_delete=False)
        books_list = []
        for i in books:
            books_dict = {
                'id': i.id,
                'btitle': i.btitle,
                "bpub_date": i.bpub_date,
                "bread": i.bread,
                "bcomment": i.bcomment
            }
            books_list.append(books_dict)
        # print(books_list)

        data = {
            'code': 0,
            'booksinfo': books_list
        }
        return JsonResponse(data)

    def post(self,request):
        body_json=request.body.decode()
        body_dict=json.loads(body_json)
        btitle=body_dict.get('btitle')
        print(btitle)
        bpub_date = body_dict.get('bpub_date')
        print(bpub_date)
        bread = body_dict.get('bread')
        bcomment = body_dict.get('bcomment')
        book = BookInfo(btitle=btitle, bpub_date=bpub_date, bread=bread, bcomment=bcomment)
        book.save()
        return JsonResponse({"code": 0, "msg": "success"})

    def put(self, request):
        body_json = request.body.decode()
        body_dict = json.loads(body_json)
        id = body_dict.get('id')
        btitle = body_dict.get('btitle')
        bpub_date = body_dict.get('bpub_date')
        bread = body_dict.get('bread')
        bcomment = body_dict.get('bcomment')
        book = BookInfo.objects.get(id=id)
        book.btitle = btitle
        book.bpub_date = bpub_date
        book.bread = bread
        book.bcomment = bcomment
        book.save()
        return JsonResponse({"code": 0, "msg": "success"})

    def delete(self, request):
        body_json = request.body.decode()
        body_dict = json.loads(body_json)
        id = body_dict.get('id')
        book = BookInfo.objects.get(id=id)
        book.is_delete = True
        book.save()
        return JsonResponse({"code": 0, "msg": "success"})
